﻿using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using Core.AdminGroupMenuPermission;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.News;

namespace CMS.Controls.News
{
    public partial class NewsManager1 : AuthenticatedControl
    {
        #region Variables

        protected string Tab;
        protected string Keyword;
        protected string StartDate;
        protected string EndDate;
        protected string Url;
        protected int PageIndex;
        protected int PageSize;
        protected int Draft;
        protected int WaitingForPublish;
        protected int Publish;
        protected int Removed;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            Tab = Utils.GetIdFromRequestString(Utils.Tab, string.Empty);

            if (string.IsNullOrEmpty(Tab))
                Response.Redirect(UrlHelpers.ListTab(cControl.AdminMenuId, Utils.IsPublished));

            Keyword = Utils.GetIdFromRequestString(Utils.Keyword, string.Empty);
            StartDate = Utils.GetIdFromRequestString(Utils.StartDate, string.Empty);
            EndDate = Utils.GetIdFromRequestString(Utils.EndDate, string.Empty);
            PageIndex = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize = Utils.GetIdFromRequestString(Utils.PageSize, ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
            Url = HttpUtility.UrlEncode(Request.Url.ToString());

            if (!IsPostBack)
            {
                InitArticle();
                ListData();
                GetStatistics();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            Draft = NewsController.News_GetStatistic((int)NewsType.Normal, StatusHelper.IsDraft);
            WaitingForPublish = NewsController.News_GetStatistic((int)NewsType.Normal, StatusHelper.IsWaitingForPublish);
            Publish = NewsController.News_GetStatistic((int)NewsType.Normal, StatusHelper.IsPublished);
            Removed = NewsController.News_GetStatistic((int)NewsType.Normal, StatusHelper.IsRemoved);
        }

        #endregion

        #region Bind Data

        private void InitArticle()
        {
            var isShowPublished = false;
            var isHighlightCategory = false;
            var isHighlightHomePage = false;

            var adminGroupMenuPermission =
                    AdminGroupMenuPermissionController.AdminGroupMenuPermission_GetBy_AdminUserId_AdminMenuId(CurrentUser.AdminUserId, cControl.AdminMenuId);
            if (adminGroupMenuPermission.Count > 0)
            {
                foreach (var agmp in adminGroupMenuPermission)
                {
                    isShowPublished = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanPublish);
                    isHighlightCategory = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanHighlightCategory);
                    isHighlightHomePage = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanHighlightHomePage);
                }
            }

            // Right context menu in gridList
            var contextMenu = new StringBuilder();
            if (isHighlightHomePage || isHighlightCategory)
            {
                contextMenu.Append("<ul id=\"myMenu\" class=\"contextMenu\">");

                if (isHighlightHomePage)
                    contextMenu.Append("<li class=\"highlights-homepage\"><a href=\"#homepage\">Nổi bật trang chủ</a></li>");

                if (isHighlightCategory)
                    contextMenu.Append("<li class=\"highlights-category\"><a href=\"#category\">Nổi bật chuyên mục</a></li>	");

                contextMenu.Append("<li class=\"highlights-remove\"><a href=\"#remove\">Xóa</a></li>");

                contextMenu.Append("</ul>");

                ltContextMenu.Text = contextMenu.ToString();
            }

            hfTab.Value = Tab;
            if (!string.IsNullOrEmpty(hfTab.Value))
            {
                switch (hfTab.Value)
                {
                    case "IsRemoved":
                        hfStatus.Value = StatusHelper.IsRemoved.ToString();
                        btnRestore.Visible = isShowPublished;
                        btnDelete.Visible = isShowPublished;
                        break;
                    case "IsWaitingForPublish":
                        hfStatus.Value = StatusHelper.IsWaitingForPublish.ToString();
                        btnPublish.Visible = isShowPublished;
                        btnRemove.Visible = isShowPublished;
                        break;
                    case "IsPublished":
                        hfStatus.Value = StatusHelper.IsPublished.ToString();
                        btnRemove.Visible = isShowPublished;
                        break;
                    case "IsDraft":
                        hfStatus.Value = StatusHelper.IsDraft.ToString();
                        btnPublish.Visible = isShowPublished;
                        btnSend.Visible = true;
                        btnDelete.Visible = true;
                        break;
                }
            }
            else
            {
                btnSend.Enabled = false;
                btnPublish.Enabled = false;
                btnDelete.Enabled = false;
                btnRemove.Enabled = false;
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Không lấy được dữ liệu.", MessageType.Failure);
            }
        }

        private void ListData()
        {
            var currentKeyword = UnicodeUtility.DecodeFrom64(Keyword);
            if (currentKeyword.IndexOf("Từ khóa") == -1)
                currentKeyword = string.Empty;

            var currentStartDate = UnicodeUtility.DecodeFrom64(StartDate);
            var currentEndDate = UnicodeUtility.DecodeFrom64(EndDate);

            lvList.DataSource = NewsController.News_GetListByTypeByStatusPaging(currentKeyword,
                                                                                ConvertUtility.ToDateTime(currentStartDate, Constants.MinDate),
                                                                                ConvertUtility.ToDateTime(currentEndDate, Constants.MaxDate),
                                                                                (int)NewsType.Normal,
                                                                                ConvertUtility.ConvertTo<int>(hfStatus.Value),
                                                                                PageIndex, PageSize);
            lvList.DataBind();

            var totalRecords = NewsController.News_Count(currentKeyword,
                                                        ConvertUtility.ToDateTime(currentStartDate, Constants.MinDate),
                                                        ConvertUtility.ToDateTime(currentEndDate, Constants.MaxDate),
                                                        (int)NewsType.Normal,
                                                        ConvertUtility.ConvertTo<int>(hfStatus.Value));

            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                UrlHelpers.ListSearch(cControl.AdminMenuId, Keyword, hfTab.Value, StartDate, EndDate, "{0}", PageSize));

            txtKeyword.Value = currentKeyword;
            ddlPageSize.SelectedValue = PageSize.ToString();
            if (!string.IsNullOrEmpty(currentStartDate) && currentStartDate != Constants.MaxDate.ToString())
            {
                txtStartDate.Value = DateTimeFunctions.FormatIn_DDMMYYYY(ConvertUtility.ToDateTime(currentStartDate));
                txtEndDate.Value = DateTimeFunctions.FormatIn_DDMMYYYY(ConvertUtility.ToDateTime(currentEndDate));
            }
        }

        protected void lvList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var ltImage = (Literal)e.Item.FindControl("ltImage");
                var status = ConvertUtility.ConvertTo<int>(((HiddenField)e.Item.FindControl("hfStatus")).Value);

                var imgIcon = "<img src=\"\" class=\"floatright mr5 topDir\" title=\"\" alt=\"\"/>";

                if (StatusHelper.IsChecked(status, StatusHelper.IsHighlightHomePage))
                    imgIcon = "<img src=\"/images/icons/color/pin.png\" class=\"floatright mr5 topDir btn14\" title=\"Nổi bật trang chủ\" alt=\"\"/>";

                if (StatusHelper.IsChecked(status, StatusHelper.IsHighlightCategory))
                    imgIcon = "<img src=\"/images/icons/color/paper-clip.png\" class=\"floatright mr5 topDir btn14\" title=\"Nổi bật chuyên mục\" alt=\"\"/>";

                ltImage.Text = imgIcon;
            }
        }

        #endregion

        #region Action

        private void UpdateStatus(int status)
        {
            ltMessage.Text = string.Empty;
            var count = 0;
            foreach (ListViewDataItem lvi in lvList.Items)
            {
                var cbItem = (CheckBox)lvi.FindControl("cbItem");
                if (cbItem == null || !cbItem.Checked) continue;

                count++;
                var id = ConvertUtility.ConvertTo<long>(lvList.DataKeys[lvi.DisplayIndex].Value);
                if (id > 0)
                    NewsController.News_Update_Status(id, status, CurrentUser.Username);
            }

            if (count == 0)
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn chưa chọn bài viết nào.", MessageType.Warning);

            ListData();
            GetStatistics();
        }

        protected void BtnSend(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsWaitingForPublish);
        }

        protected void BtnPublish(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsPublished);
        }

        protected void BtnRestore(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsDraft);
        }

        protected void BtnRemove(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsRemoved);
        }

        protected void BtnDelete(object sender, EventArgs e)
        {
            UpdateStatus(StatusHelper.IsDeleted);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            RedirectLink(PageSize);
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink(ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
        }

        public void RedirectLink(int currentPageSize)
        {
            DateTime startDate;
            if (txtStartDate.Value != "Từ ngày" && txtStartDate.Value != "")
                startDate = DateTimeFunctions.ValidDateTime(txtStartDate.Value, "00:00:00");
            else
                startDate = DateTime.MaxValue;

            DateTime endDate;
            if (txtEndDate.Value != "Đến ngày" && txtEndDate.Value != "")
                endDate = DateTimeFunctions.ValidDateTime(txtEndDate.Value, "23:59:59");
            else
                endDate = DateTimeFunctions.ValidDateTime(string.Format("{0}/{1}/{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year), "23:59:59");

            var keyword = txtKeyword.Value.IndexOf("Từ khóa") != -1 ? string.Empty : txtKeyword.Value;

            Response.Redirect(UrlHelpers.ListSearch(cControl.AdminMenuId,
                                                        UnicodeUtility.EncodeTo64UTF8(keyword),
                                                        hfTab.Value,
                                                        UnicodeUtility.EncodeTo64UTF8(startDate.ToString()),
                                                        UnicodeUtility.EncodeTo64UTF8(endDate.ToString()),
                                                        SettingValues.PageIndex.ToString(), currentPageSize));
        }

        #endregion
    }
}